package com.tanhua.server.service;

import com.github.tobato.fastdfs.FdfsClientConstants;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.FollowUser;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class VideoService {

    @Reference
    private VideoApi videoApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private VideoMQService videoMQService;

    //小视频列表业务
    @Cacheable(value = "videoList", key = "#page+'_'+#pagesize")
    public PageResult queryVideos(Integer page, Integer pagesize) {

        PageResult pageResult = videoApi.queryVideos(page, pagesize);
        List<Video> items = (List<Video>) pageResult.getItems();

        ArrayList<VideoVo> videoVos = new ArrayList<>();
        if (items != null) {
            for (Video item : items) {
                VideoVo videoVo = new VideoVo();
                BeanUtils.copyProperties(item, videoVo);
                UserInfo userInfo = userInfoApi.findById(item.getUserId());
                if (userInfo != null) {
                    BeanUtils.copyProperties(userInfo, videoVo);
                }
                if (item.getPicUrl() != null) {
                    videoVo.setCover(item.getPicUrl());
                }
                videoVo.setId(item.getId().toString());

                String key = "followUser_" + UserHolder.getUserId() + "_" + videoVo.getUserId();
                if (redisTemplate.hasKey(key)) {
                    videoVo.setHasFocus(1);
                } else {
                    videoVo.setHasFocus(0);
                }


                if (item.getText() != null) {
                    videoVo.setSignature(item.getText());
                }
                videoVo.setHasLiked(0);
                videoVos.add(videoVo);
            }
        }
        System.out.println("从数据库中查询============================");
        pageResult.setItems(videoVos);
        return pageResult;
    }

    //大数据推送分页
    public PageResult findRecommend(Integer page, Integer pagesize, Long userId) {
        PageResult pageResult = null;
        String key = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String s = redisTemplate.opsForValue().get(key);

        if (StringUtils.isEmpty(s)) {
            return null;
        }

        String[] vids = s.split(",");
        int startIndex = (page - 1) * pagesize;
        if (startIndex < vids.length) {
            int endIndex = startIndex + pagesize - 1;
            if (endIndex >= vids.length) {
                endIndex = vids.length - 1;
            }
            ArrayList<Long> vidList = new ArrayList<>();
            for (int i = startIndex; i <= endIndex; i++) {
                vidList.add(Long.valueOf(vids[i]));
            }
            List<Video> videos = videoApi.findByVids(vidList);
            pageResult = new PageResult(page,pagesize,vidList.size(),videos);

        }
        return pageResult;
    }

    //上传小视频功能业务
    @CacheEvict(value = "videoList", allEntries = true)
    public ResponseEntity<Object> uploadVideo(MultipartFile videoThumbnail, MultipartFile videoFile, String text) throws IOException {
        //视频封面上传到阿里云
        String originalFilename = videoThumbnail.getOriginalFilename();
        String pirUrl = ossTemplate.upload(originalFilename, videoThumbnail.getInputStream());

        //视频本体上传到Fdfs
        String videoFilename = videoFile.getOriginalFilename();
        String ext = videoFilename.substring(videoFilename.lastIndexOf(".") + 1);
        StorePath storePath = fastFileStorageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), ext, null);
        //获得视频url
        String url = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        log.info("videoUrl = " + url);
        log.info("picUrl" + pirUrl);

        //将url传入Mongo
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        if (text != null) {
            video.setText(text);
        } else {
            video.setText("歪比巴布");
        }
        video.setPicUrl(pirUrl);
        video.setVideoUrl(url);
        video.setCreated(System.currentTimeMillis());
        video.setLikeCount(0);
        video.setCommentCount(0);
        video.setLoveCount(0);

        videoApi.save(video);

        //发送mq消息
        videoMQService.videoMsg(video.getId().toString());

        return ResponseEntity.ok(null);
    }

    //视频用户关注业务
    @CacheEvict(value = "videoList", allEntries = true)
    public ResponseEntity<Object> userFocus(Long followUserId) {
        //将FollowUser放入Mongo
        FollowUser followUser = new FollowUser();
        followUser.setUserId(UserHolder.getUserId());
        followUser.setFollowUserId(followUserId);
        followUser.setCreated(System.currentTimeMillis());
        videoApi.followUser(followUser);

        //存入redis，用于查询是否关注
        String key = "followUser_" + UserHolder.getUserId() + "_" + followUser.getFollowUserId();
        redisTemplate.opsForValue().set(key, "1");

        return ResponseEntity.ok(null);
    }

    //取消视频用户关注业务
    @CacheEvict(value = "videoList", allEntries = true)
    public ResponseEntity<Object> userUnFocus(Long followUserId) {
        FollowUser followUser = new FollowUser();
        followUser.setUserId(UserHolder.getUserId());
        followUser.setFollowUserId(followUserId);

        String key = "followUser_" + UserHolder.getUserId() + "_" + followUserId;
        redisTemplate.delete(key);
        videoApi.deleteFollow(followUser);
        return ResponseEntity.ok(null);
    }


}
